from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import time
from selenium.common.exceptions import InvalidArgumentException, WebDriverException, NoSuchElementException


class Base:
    def __init__(self, browser):
        # 打开浏览器
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
            self.driver.maximize_window()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
            self.driver.maximize_window()
        elif browser == 'edge':
            self.driver = webdriver.Edge()
            self.driver.maximize_window()
        else:
            print('不支持该浏览器')

    def get(self, url):
        # 输入网址
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print('输入的网址有误')

    def find_element(self, locator):
        # 定位元素
        try:
            return self.driver.find_element(*locator)
        except NoSuchElementException:
            print('元素定位失败')

    def get_attribute(self, locator, value):
        # 定位属性
        try:
            element = self.driver.find_element(locator, value)
            print(element.get_attribute('outerHTML'))
        except NoSuchElementException:
            print('没有定位到元素')

    def forward(self):
        # 前进
        self.driver.forward()

    def back(self):
        # 后退
        self.driver.back()

    def refresh(self):
        # 刷新
        self.driver.refresh()

    def click(self, locator):
        # 点击操作
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print('点击元素定位失败')

    def quit(self, seconds=0):
        # 退出
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    base = Base('chrome')
    base.get('https://www.baidu.com')
    # base.get_attribute(By.ID, 'kw')
    base.forward()
    base.back()
    base.refresh()
